import os
from typing import Optional
from docx import Document as DocxDocument
from PyPDF2 import PdfReader
import pandas as pd
from openpyxl import load_workbook

class FileProcessor:
    """文件处理器基类"""
    @staticmethod
    def get_processor(filepath: str) -> 'FileProcessor':
        """根据文件类型返回对应的处理器"""
        ext = os.path.splitext(filepath)[1].lower()
        return {
            '.txt': TextProcessor,
            '.pdf': PDFProcessor,
            '.doc': DocProcessor,
            '.docx': DocProcessor,
            '.csv': CSVProcessor,
            '.xlsx': ExcelProcessor,
            '.xls': ExcelProcessor
        }.get(ext, TextProcessor)(filepath)

    def __init__(self, filepath: str):
        self.filepath = filepath
        self.max_size = 10 * 1024 * 1024  # 10MB

    def check_file_size(self) -> bool:
        """检查文件大小是否超限"""
        return os.path.getsize(self.filepath) <= self.max_size

    def read(self) -> str:
        """读取文件内容"""
        if not self.check_file_size():
            raise ValueError("File size exceeds 10MB limit")
        return self._read()

    def _read(self) -> str:
        """具体的读取实现"""
        raise NotImplementedError

class TextProcessor(FileProcessor):
    """文本文件处理器"""
    def _read(self) -> str:
        try:
            with open(self.filepath, 'r', encoding='utf-8') as f:
                return f.read()
        except UnicodeDecodeError:
            # 如果UTF-8失败，尝试其他编码
            encodings = ['gbk', 'gb2312', 'latin1']
            for encoding in encodings:
                try:
                    with open(self.filepath, 'r', encoding=encoding) as f:
                        return f.read()
                except UnicodeDecodeError:
                    continue
            raise ValueError("Unable to decode file with supported encodings")

class PDFProcessor(FileProcessor):
    """PDF文件处理器"""
    def _read(self) -> str:
        reader = PdfReader(self.filepath)
        text = []
        for page in reader.pages:
            text.append(page.extract_text())
        return '\n'.join(text)

class DocProcessor(FileProcessor):
    """Word文档处理器"""
    def _read(self) -> str:
        doc = DocxDocument(self.filepath)
        return '\n'.join([paragraph.text for paragraph in doc.paragraphs])

class CSVProcessor(FileProcessor):
    """CSV文件处理器"""
    def _read(self) -> str:
        try:
            df = pd.read_csv(self.filepath)
            # 检查必要的列是否存在
            required_columns = {'index', 'content'}
            if not required_columns.issubset(df.columns):
                missing = required_columns - set(df.columns)
                raise ValueError(f"Missing required columns: {', '.join(missing)}")
            
            # 只处理 content 列
            return '\n\n'.join(df['content'].fillna('').astype(str).tolist())
        except Exception as e:
            raise ValueError(f"Error processing CSV file: {str(e)}")

class ExcelProcessor(FileProcessor):
    """Excel文件处理器"""
    def _read(self) -> str:
        try:
            df = pd.read_excel(self.filepath)
            # 检查必要的列是否存在
            required_columns = {'index', 'content'}
            if not required_columns.issubset(df.columns):
                missing = required_columns - set(df.columns)
                raise ValueError(f"Missing required columns: {', '.join(missing)}")
            
            # 只处理 content 列
            return '\n\n'.join(df['content'].fillna('').astype(str).tolist())
        except Exception as e:
            raise ValueError(f"Error processing Excel file: {str(e)}") 